package au.com.handsunited.aop.notifications;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import au.com.handsunited.model.User;
import au.com.handsunited.model.invitations.Invitation;
import au.com.handsunited.service.EmailService;

/**
 *
 * @author Arun Chandrasekhar
 */
@Aspect
public class UserNotificationsAdvice {

	private final EmailService emailService;

	private static Logger logger = LoggerFactory.getLogger(UserNotificationsAdvice.class);


	/**
	 * @param emailService
	 */
	public UserNotificationsAdvice(EmailService emailService) {
		super();
		this.emailService = emailService;
	}

	/**
	 *
	 */
	@Pointcut("execution(* au.com.handsunited.service.impl.UserServiceImpl.createUser(..))")
	public void registered(JoinPoint joinPoint, final User user) {

	    Map<String, Object> model = new HashMap<String, Object>();
	    model.put("user", user);
		emailService.sendEmail(user.getContactInfo().getEmailAddress(), "velocity/emails/user/register.vm", "Welcome to Hands United", model);
	}

	/**
	 *
	 * @param user
	 */
	@Pointcut("execution(* au.com.handsunited.service.impl.UserServiceImpl.updateUser(..))")
	public void profileUpdated(final User user) {

	    Map<String, Object> model = new HashMap<String, Object>();
	    model.put("user", user);
		emailService.sendEmail(user.getContactInfo().getEmailAddress(), "velocity/emails/user/profileUpdated.vm", "Your profile has been updated", model);
	}


	/**
	 *
	 * @param invitationsMap
	 */
	@Pointcut("execution(* au.com.handsunited.service.impl.UserServiceImpl.inviteUsers(..))")
	public void userInvitations(final Map<String, List<Invitation>> invitationsMap) {

		List<Invitation> validInvitations = invitationsMap.get(Invitation.VALID_EMAILADDRESSES);

		for (Invitation invitation : validInvitations) {
			Map<String, Object> model = new HashMap<String, Object>();
			model.put("from", invitation.getFrom());
			model.put("message", invitation.getMessage());
			model.put("inviteeEmailAddress", invitation.getNonMemberInviteeEmailAddress());
			emailService.sendEmail(
					invitation.getNonMemberInviteeEmailAddress(), "velocity/emails/user/invite.vm",
					invitation.getFrom().getName() + " has invited you to join Hands United!", model);
		}

	}


}
